package guzb.cnblogs.security.industrydemo.auth;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;

/**
 * 自定义的用户明细服务
 * 这里没有加@Service、@Component等类似注解，
 * 其装配过程写在了WebSecurityBeanConfig中，目的就是为了集中演示Security组件的装配
 */
public class MyUserDetailsService implements UserDetailsService {

    private SecurityMapper userEntityMapper;

    public MyUserDetailsService(SecurityMapper userEntityMapper) {
        this.userEntityMapper = userEntityMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userEntityMapper.getByUsername(username);
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户 " + username + " 不存在");
        }

        List<AuthorityEntity> authorityEntityList = userEntityMapper.listAuthoritiesOfUser(userEntity.getId());
        return new MyUserDetails(userEntity, authorityEntityList);
    }
}
